package com.bawei.module_goods.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.module_goods.intent.GoodsDetailIntent
import com.bawei.module_goods.repository.GoodsDetailRepository
import com.bawei.module_goods.state.GoodsState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch


class GoodsDetailViewModel : BaseViewModel<GoodsDetailIntent>() {
    private val repo: GoodsDetailRepository by lazy { GoodsDetailRepository() }
    private var _detailStateFlow = MutableStateFlow<GoodsState>(GoodsState.Init)
    val goodsDetailStateFlow = _detailStateFlow.asStateFlow()

    private var _detailCommentStateFlow = MutableStateFlow<GoodsState>(GoodsState.Init)
    val goodsDetailCommentStateFlow = _detailCommentStateFlow.asStateFlow()

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect { intent ->
                when (intent) {
                    is GoodsDetailIntent.DetailIntent -> {
                        loadHomeData(intent.goodsId)
                    }
                    is GoodsDetailIntent.DetailCommentIntent -> {
                        getDeleteComment(intent.goodsId, intent.pageNum, intent.pageSize)
                    }
                }
            }
        }
    }

    fun loadHomeData(goodsId : Int) {
        viewModelScope.launch {
            // Banner
            repo.getGoodsDetail(goodsId)
                .catch {
                    _detailStateFlow.value = GoodsState.onFailed(it.message.toString())
                }.filter { it != null }
                .collect {
                    if ((it.code == 0 || it.code == 200) && it.data != null) {
                        _detailStateFlow.value = GoodsState.onSuccess(it.data!!, "detail")
                    } else {
                        _detailStateFlow.value = GoodsState.onFailed(it.msg)
                    }
                }
        }
    }
    fun getDeleteComment(goodsId : Int, pageNum: Int, pageSize: Int) {
        viewModelScope.launch {
            // Banner
            repo.getDetailComment(goodsId, pageNum, pageSize)
                .catch {
                    _detailCommentStateFlow.value = GoodsState.onFailed(it.message.toString())
                }.filter { it != null }
                .collect {
                    if ((it.code == 0 || it.code == 200) && it.data != null) {
                        _detailCommentStateFlow.value = GoodsState.onSuccess(it.data, "comment")
                    } else {
                        _detailCommentStateFlow.value = GoodsState.onFailed(it.msg)
                    }
                }
        }
    }
} 